var post_apis = {
	moduleList: "http://api.fangchepingtai.com/fangchebbs/user/module/listall",
	createPost: "http://api.fangchepingtai.com/fangchebbs/user/post/create"
};
(function() {
	var editor;

	require(["ueditor"], function() {
		// 初始化编辑器
		editor = UE.getEditor('container');
	});

	// 修改选择版块
	App.set("$Event.post.select_post_module", function() {
		var _module = App.get("$Cache.post.module_list")[this.value] || {};
		App.set("$Cache.post.new._module", _module._id);
		App.set("$Cache.post.new._module_name", _module.name);
	});

	require(['/js/tools/image_upload.js'], function(upload) {
		// 上传话题图片
		App.set("$Event.post.upload_preview", function() {
			App.set("$Cache.post.uploading_post_preview", true);
			var file = this.files[0];
			// var dtd = new $.Deferred();
			if (file) {
				upload(file, function(path) {
					App.set("$Cache.post.new.preview_img", path);
					App.set("$Cache.post.uploading_post_preview", false);
				});
			} else {
				App.set("$Cache.post.uploading_post_preview", false);
			};
		});
	});

	// 获取ueditor内容
	App.set("$Event.post.submit_post", function() {
		var detail = editor.getContent();
		if (!detail) {
			alert("warn", "请输入话题内容");
			return;
		};
		if (!App.get("$Cache.post.new.title")) {
			alert("warn", "请输入话题标题");
			return;
		};
		if (!App.get("$Cache.post.new._module")) {
			alert("warn", "请选择话题版块");
			return;
		};
		var data = App.get("$Cache.post.new");
		data.detail = detail;
		var posturl = post_apis.createPost;
		coAjax.post(posturl, data, function(result) {
			alert("success", "话题创建成功");
			console.log(result);
			App.set("$Cache.post.new", "");
			editor.setContent("");
			document.body.scrollTop = 0;
		}, function(err, errMsg, errCode) {
			console.log(err);
			console.log(errMsg);
		});
	});

	Path.on("/__basename__.html", function(_current_location) {
		var qs = _current_location.query;

		// 获取所有版块列表
		coAjax.get(post_apis.moduleList, function(result) {
			console.log(result);
			App.set("$Cache.post.module_list", result);
		}, function(err, errMsg, errCode) {
			console.log(err);
			console.log(errMsg);
		});
	});
}());